package com.juku2024.juku

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import androidx.recyclerview.widget.RecyclerView
import com.juku2024.juku.base.BaseActivity
import com.juku2024.juku.viewmodel.FeedbackViewModel
import com.juku2024.juku.adapter.FeedbackAdapter
import com.juku2024.juku.callback.OnNoDoubleClickListener
import com.juku2024.juku.model.FeedbackInfo
import com.juku2024.juku.model.SysMsg
import com.juku2024.juku.tools.*
import com.juku2024.juku.widget.LoadingView

class FeedbackActivity : BaseActivity(), OnNoDoubleClickListener {

    private lateinit var feedbackSendTv: View
    private lateinit var feedbackRc: RecyclerView
    private lateinit var loadingView: LoadingView
    private lateinit var feedbackInputEt: EditText

    private val adapter by lazy { FeedbackAdapter(ArrayList()) }
    private val viewModel by lazy { getViewModel(FeedbackViewModel::class.java) }

    override fun getLayoutResId(): Int {
        return R.layout.activity_feedback
    }


    override fun initView() {
        feedbackRc = findViewById(R.id.feedback_rc)
        feedbackSendTv = findViewById(R.id.feedback_send_tv)
        loadingView = findViewById(R.id.loadingView_feedback)
        feedbackInputEt = findViewById(R.id.feedback_input_et)


        feedbackRc.layoutManager = WrapLinearLayoutManager(this)
        feedbackRc.adapter = adapter
        adapter.setHeaderView(LayoutInflater.from(this).inflate(R.layout.item_feedback_empty, null))
    }

    override fun init(savedInstanceState: Bundle?) {
        if (!NetworkUtils.isNetworkConnected()) {
            showError()
            return
        }
        loadingView.showLoading()
        // 请求历史反馈消息
        doHttpFeedback()
    }

    override fun bindEvent() {
        super.bindEvent()
        feedbackSendTv.setOnClickListener(this)
    }

    override fun onNoDoubleClick(v: View?) {
        when (v!!.id) {
            R.id.feedback_send_tv -> {
                val text = feedbackInputEt.text.toString()
                if (TextUtils.isEmpty(text) || TextUtils.isEmpty(text.trim())) {
                    AlertUtils.alert(AppUtils.getString(R.string.input_feedback_content))
                    return
                }
                val replace = text.replace("[", "{")
                val replaceStr = replace.replace("]", "}")
                if (!NetworkUtils.isNetworkConnected()) {
                    AlertUtils.alert(AppUtils.getString(R.string.error_net))
                    return
                }

                loadingView.showLoading()
                feedbackSendTv.isEnabled = false
                doHttpPostFeedback(replaceStr.trim())

                feedbackInputEt.postDelayed({
                    AppUtils.closeKeyboard(feedbackInputEt)
                }, 500)
            }
        }
    }

    private fun showError() {
        showErrorDialog(
            AppUtils.getString(R.string.feedback_error),
            AppUtils.getString(R.string.confirm),
            {
                hideErrorDialog()
                doHttpFeedback()
                loadingView.showLoading()
            }, AppUtils.getString(R.string.cancel), {
                hideErrorDialog()
            })
    }

    private fun showError1() {
        showErrorDialog(
            getString(R.string.feedback_post_error),
            getString(R.string.confirm), {
                hideErrorDialog()
                doHttpFeedback()
                loadingView.showLoading()
            }, AppUtils.getString(R.string.cancel), {
                hideErrorDialog()
            })
    }


    private fun doHttpFeedback() {
        LogC.e("当前时间 -> " + System.currentTimeMillis())
        viewModel.fetchFeedback({
            if (isActivityNotActive()) return@fetchFeedback
            loadingView.hideLoading()
            var feedbacks = it.feedbacks
            val sysmsg = it.sysmsg
            if (feedbacks != null) {
                if (sysmsg?.content != null) {
                    //发送服务器已读系统消息
                    doHttpSendMsg(sysmsg)
                    val feedbackInfo = FeedbackInfo()
                    feedbackInfo.actionDate = System.currentTimeMillis() / 1000L
                    feedbackInfo.msg = sysmsg.content
                    feedbackInfo.roleId = Constants.ROLE_SYSTEM
                    feedbacks.add(feedbackInfo)
                }
            } else {
                if (sysmsg == null) {
                    showError()
                    return@fetchFeedback
                } else {
                    val feedbackInfo = FeedbackInfo()
                    feedbackInfo.actionDate = System.currentTimeMillis() / 1000L
                    feedbackInfo.msg = sysmsg.content
                    feedbackInfo.roleId = Constants.ROLE_SYSTEM
                    feedbacks = mutableListOf(feedbackInfo)
                    //发送服务器已读系统消息
                    doHttpSendMsg(sysmsg)
                }
            }

            //请求成功，且不为空
            adapter.setList(feedbacks)
            feedbackRc.post {
                feedbackRc.scrollToPosition(adapter.data.size)
            }


            // 如果最后一条消息是用户消息，也要开启轮训
            if (feedbacks.isNotEmpty()) {
                // 判断最后一条消息是否是用户消息，是的话，也得开启轮训
                val lastMsg = feedbacks.last()
                if (lastMsg.roleId != Constants.ROLE_SYSTEM) {
                    isStartCheckNewSystemMsg = true
                    checkHasNewSystemMsg()
                }
            }
        }, {
            if (isActivityNotActive()) return@fetchFeedback
            loadingView.hideLoading()
            showError()
        })
    }

    private fun doHttpSendMsg(sysmsg: SysMsg) {
        viewModel.requestSendSystemMsgRead(sysmsg, {}, {})
    }

    private fun doHttpPostFeedback(text: String) {
        viewModel.postFeedback(text, {
            if (isActivityNotActive()) return@postFeedback
            loadingView.hideLoading()
            feedbackSendTv.isEnabled = true
            //发送成功
            refreshUI(it)

            // 开启轮训检查是否有系统消息回复, 没3s一次查询
            if (isStartCheckNewSystemMsg) return@postFeedback
            isStartCheckNewSystemMsg = true
            checkHasNewSystemMsg()
        }, {
            if (isActivityNotActive()) return@postFeedback
            feedbackSendTv.isEnabled = true
            loadingView.hideLoading()
            showError1()
        })
    }


    private fun refreshUI(feedbackInfo: FeedbackInfo) {
        feedbackInputEt.setText("")
        adapter.addData(feedbackInfo)
        loadingView.postDelayed({
            feedbackRc.layoutManager?.smoothScrollToPosition( feedbackRc, null, adapter.data.size)
        }, 500)
    }


    // 是否开启了轮训查新消息
    private var isStartCheckNewSystemMsg = false
    private fun checkHasNewSystemMsg(){
        LogC.e("反馈 -> 开启轮训")
        viewModel.hasNewSystemMsg { hasNewSystemMsg ->
            if (!hasNewSystemMsg) {
                LogC.e("反馈 -> 没有系统反馈，继续轮训")
                checkHasNewSystemMsg()
                return@hasNewSystemMsg
            }
            LogC.e("反馈 -> 有新的系统消息")
            isStartCheckNewSystemMsg = false
            doHttpFeedback()
        }
    }


    override fun onDestroy() {
        super.onDestroy()
    }

}